Page({
  data: {
    isSwitch:true,
    userId: '',
    ageArr: ['全部', '1个月', '1-3个月', '3-6个月'],
    region: ['', '', ''],
    publishList: [],
    activeIndex: 0,
    activeIndex1: 0,
    ageIndex: 0,
    num: 0,
    userInfo: {
      nickname: '',
      address: [],
      phone: ''
    },
    petAdopt: {
      petImg: [],
      petname: '',
      planet: '汪星人',
      breed: '',
      gender: '男生',
      age: '',
      medical: [],
      features: [],
      describe: '',
      demand: [],
    }
  },
  goLogin() {
    wx.navigateTo({
      url: '../login/login',
    })
  },
  getToken() {
    if (wx.getStorageSync('token')) {
    } else {
      wx.showToast({
        title: '账号未登录，即将跳到登录页',
        icon: 'none'
      })
      setTimeout(() => {
        this.goLogin()
      }, 2000)
    }
  },
  getPublishList() {
    wx.cloud.callFunction({
      name: 'get-publish-pet-list',
    }).then(res => {
      // console.log('res ==> ', res);
      this.data.publishList = res.result.data[0]
      this.setData({
        publishList: res.result.data[0]
      })
      // console.log(this.data.publishList);
    }).catch(err => {
      console.log('err ==> ', err);
    })
  },
  getAc(e) {
    if (this.data.activeIndex === e.currentTarget.dataset.index) {
      return;
    }
    this.setData({
      activeIndex: e.currentTarget.dataset.index
    })
    let key = e.currentTarget.dataset.key;
    this.data.petAdopt[key] = e.currentTarget.dataset.item;
    // this.data.activeIndex = e.currentTarget.dataset.index;
    // console.log(e.currentTarget.dataset.index);
  },
  getAc1(e) {
    if (this.data.activeIndex1 === e.currentTarget.dataset.index) {
      return;
    }
    this.setData({
      activeIndex1: e.currentTarget.dataset.index
    })
    let key = e.currentTarget.dataset.key;
    this.data.petAdopt[key] = e.currentTarget.dataset.item;
  },
  getIsActive(e) {
    this.setData({
      ["publishList.medical[" + e.currentTarget.dataset.index + "].selected"]: !this.data.publishList.medical[e.currentTarget.dataset.index].selected
    })
    if (this.data.petAdopt.medical.indexOf(e.currentTarget.dataset.item.name) > -1) {
      this.data.petAdopt.medical.splice(this.data.petAdopt.medical.indexOf(e.currentTarget.dataset.item.name), 1)
    } else {
      this.data.petAdopt.medical.push(e.currentTarget.dataset.item.name)
    }
  },
  getIsActive1(e) {
    if (this.data.num >= 3) {
      return
    }
    this.setData({
      ["publishList.petFeatures[" + e.currentTarget.dataset.index + "].selected"]: !this.data.publishList.petFeatures[e.currentTarget.dataset.index].selected,
    })
    if (this.data.publishList.petFeatures[e.currentTarget.dataset.index].selected == true) {
      this.setData({
        num: this.data.num + 1
      })
    } else {
      this.setData({
        num: this.data.num - 1
      })
    }
    if (this.data.petAdopt.features.indexOf(e.currentTarget.dataset.item.name) > -1) {
      this.data.petAdopt.features.splice(this.data.petAdopt.features.indexOf(e.currentTarget.dataset.item.name), 1)
    } else {
      this.data.petAdopt.features.push(e.currentTarget.dataset.item.name)
    }
  },
  getIsActive3(e) {
    this.setData({
      ["publishList.demand[" + e.currentTarget.dataset.index + "].selected"]: !this.data.publishList.demand[e.currentTarget.dataset.index].selected
    })
    if (this.data.petAdopt.demand.indexOf(e.currentTarget.dataset.item.name) > -1) {
      this.data.petAdopt.demand.splice(this.data.petAdopt.demand.indexOf(e.currentTarget.dataset.item.name), 1)
    } else {
      this.data.petAdopt.demand.push(e.currentTarget.dataset.item.name)
    }
  },
  onLoad(options) {},
  onShow() {
    this.getPublishList()
    this.getLoginUser()
    this.getToken()
  },
  getLoginUser() {
    let token = wx.getStorageSync('token');
    // console.log('token ==> ', token);
    if (!token) {
      return;
    }
    wx.cloud.callFunction({
      name: 'get-user-login',
      data: {
        token
      }
    }).then(res => {
      // console.log(res);
      let tokenData = res.result.data
      for (let i = 0; i < tokenData.length; i++) {
        if (tokenData[i].token == token) {
          this.setData({
            ['userId']: tokenData[i].userId
          })
        }
      }
      this.getUser(this.data.userId)
      // console.log('this.data.userId ==> ', this.data.userId);
    }).catch(err => {
      console.log(err);
    })
  },
  getUser(userId) {
    wx.cloud.callFunction({
      name: 'get-user',
      data: {
        userId: userId
      }
    }).then(res => {
      // console.log('res66 ==>', res);
      this.setData({
        ['userInfo.phone']: res.result.data[0].phone,
        // ['userInfo.address']: res.result.data[0].address,
      })
      if (res.result.data[0].nickname != "") {
        this.setData({
          ['userInfo.nickname']: res.result.data[0].nickname,
        })
      } else {
        this.setData({
          ['userInfo.nickname']: '',
        })
      }
      if (res.result.data[0].address != []) {
        this.setData({
          region: res.result.data[0].address,
          ['userInfo.address']:res.result.data[0].address,
        })
      } else {
        this.setData({
          region: ['', '', ''],
          ['userInfo.address']:['', '', '']
        })
      }

    }).catch(err => {
      console.log('err66 ==> ', err);
    })
  },
  selectImg() {
    if (this.data.petAdopt.petImg.length >= 6) {
      return
    }
    wx.chooseMedia({
      count: 6,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      maxDuration: 30,
      camera: 'back',
      success: res => {
        console.log('res ==> ', res);

        res.tempFiles.forEach(file => {
          //生成图片名称
          let filename = file.tempFilePath.split(/\//).pop();
          // console.log('filename ==> ', filename);

          file.filename = filename;
        })

        this.data.petAdopt.petImg.push(...res.tempFiles);

        console.log(' this.data.petAdopt.petImg ==> ', this.data.petAdopt.petImg);

        this.setData({
          ['petAdopt.petImg']: this.data.petAdopt.petImg
        })

      }
    })
  },
  updateAdopt(e) {
    let key = e.currentTarget.dataset.key;
    this.data.petAdopt[key] = e.detail.value;
    console.log(this.data.petAdopt);
  },
  updateUserInfo(e) {
    let key = e.currentTarget.dataset.key;
    this.data.userInfo[key] = e.detail.value;
    console.log(this.data.userInfo);
  },
  bindAgeChange: function (e) {
    // console.log('Age', e.detail.value)
    this.setData({
      ageIndex: e.detail.value
    })
    if (e.detail.value == 0) {
      this.setData({
        ['petAdopt.age']: ''
      })
    } else {
      this.setData({
        ['petAdopt.age']: this.data.ageArr[e.detail.value]
      })
    }
  },
  delImg(e) {
    this.data.petAdopt.petImg.splice(this.data.petAdopt.petImg.indexOf(e.currentTarget.dataset.item.tempFilePath), 1)
    this.setData({
      ["petAdopt.petImg"]: this.data.petAdopt.petImg
    })
  },
  bindRegionChange: function (e) {
    this.setData({
      region: e.detail.value,
      ['userInfo.address']: e.detail.value
    })
  },
  //确认发布
  async publish() {
    if (this.data.userInfo.nickname == '' ||
      this.data.userInfo.address == '' ||
      this.data.petAdopt.petImg == '' ||
      this.data.petAdopt.petname == '' ||
      this.data.petAdopt.breed == '' ||
      this.data.petAdopt.age == '' ||
      this.data.petAdopt.medical == '' ||
      this.data.petAdopt.features == '' ||
      this.data.petAdopt.describe == '' ||
      this.data.petAdopt.demand == ''
    ) {
      wx.showToast({
        title: '请填满宠物信息',
        icon: 'none'
      })
    } else if (
      this.data.userInfo.nickname != '' &&
      this.data.userInfo.address != '' &&
      this.data.petAdopt.petImg != '' &&
      this.data.petAdopt.petname != '' &&
      this.data.petAdopt.breed != '' &&
      this.data.petAdopt.age != '' &&
      this.data.petAdopt.medical != '' &&
      this.data.petAdopt.features != '' &&
      this.data.petAdopt.describe != '' &&
      this.data.petAdopt.demand != '') {
      //执行逻辑
      //获取token
      let token = wx.getStorageSync('token');
      console.log('token');

      if (!token) {
        return;
      }

      wx.showLoading({
        title: '加载中...',
        mask: true
      })
      let tokenData = await wx.cloud.callFunction({
        name: 'get-user-login',
        data: {
          token
        }
      })

      console.log('tokenData ==> ', tokenData);

      if (tokenData.result.data.length === 1) {
        //上传图片
        //等待所有异步任务完成后再执行其他任务
        //1. Promise.all()
        //2. aynsc await

        let imgPromise = [];

        this.data.petAdopt.petImg.forEach(img => {
          let promise = wx.cloud.uploadFile({
            cloudPath: `petImg/${img.filename}`,
            filePath: img.tempFilePath
          })

          imgPromise.push(promise);
        })

        let imgData = await Promise.all(imgPromise);

        console.log('imgData ==> ', imgData);

        let imgFileIDs = [];
        imgData.forEach(img => {
          imgFileIDs.push(img.fileID);
        })


        wx.cloud.callFunction({
          name: 'add-pet',
          data: {
            petAdopt: this.data.petAdopt,
            userInfo:this.data.userInfo,
            userId: tokenData.result.data[0].userId
          }
        }).then(res => {
          console.log('res ==> ', res);

          wx.hideLoading();

          if (res.result._id) {
            wx.showToast({
              title: '发布成功',
              icon: 'none',
              duration: 2000
            })

            wx.switchTab({
              url: '../home/home'
            })

          } else {
            wx.showToast({
              title: '发布失败',
              icon: 'none',
              duration: 2000
            })
          }

        }).catch(err => {
          wx.hideLoading();

          wx.showTabBar({
            title: '发表失败',
            icon: 'none',
            duration: 2000
          })
          console.log('err ==> ', err);
        })

      } else {
        wx.hideLoading();
      }
    }
  }
})